package com.perfect.factory;

import io.netty.util.internal.ObjectUtil;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 自定义断言
 */

@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory {

    private static String PARAM_NAME="name";

    public MyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Object config) {


        Config config1= (Config) config;
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {

                ServerHttpRequest request = serverWebExchange.getRequest();
                MultiValueMap<String, String> queryParams = request.getQueryParams();
                if(!CollectionUtils.isEmpty(queryParams)){
                    List<String> strings = queryParams.get(PARAM_NAME);
                    System.out.println(strings+config1.getValue());
                    String s = strings.get(0);
                    if(s.equals(config1.getValue())){
                        return  true;
                    }
                }

                return false;
            }
        };
    }


    /**
     * 结合这个方法，绑定Config 静态内部类的属性
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //集合里面存放 需要绑定的配置文件中的参数名
        return Collections.singletonList("value");
    }

    /**
     * 声明静态内部类，用于接收配置文件中的断言信息
     */
    public static class Config{
        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
